package cn.sfa.common.taglib;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.entity.users.SaleUsersLogin;

/**
 * 
* 类名称：HeaderTag   
* 类描述：jsp页面的头部信息自定义标签类
* 创建人：lenovo   
* 创建时间：2012-2-9 上午10:23:00     
* 修改备注：  
* @version  v1.0
 */
public class HeaderTag  extends TagSupport{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 7639660502344530437L;


	Logger logger = LoggerFactory.getLogger(HeaderTag.class);


	String menuId;
	
	@Override
	public int doEndTag() throws JspException {

		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {
		
		logger.info("--------------startTag--------------");
		
		String path = (String) pageContext.getRequest().getAttribute("path");
		
		String curURL = (String) pageContext.getRequest().getAttribute("curPath");
		
		SaleUsersLogin user = (SaleUsersLogin) pageContext.getSession().getAttribute("user");
		
		String userType = null;
		try {
			userType = user.getUserType();
			if ("USERTYPE_1".equals(userType)) {
				userType = "o1";
			} else if ("USERTYPE_2".equals(userType)) {
				userType = "o1";
			} else if ("USERTYPE_4".equals(userType)) {
				userType = "i1";
			} else if ("USERTYPE_3".equals(userType)) {
				userType = "i1";
			}
			logger.info("当前用户的类型:" + userType);
		} catch (Exception e) {
			
			HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
				try {
					response.sendRedirect(request.getContextPath()+"/sfa/sfa/index.jsp");//重定向登录页面
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
			
		}
		String navURL="";
		
		navURL = "/"+curURL.split("/sfa/")[1];//导航菜单链接
		navURL ="/"+navURL.split("/")[1]+"/index";
		
		String menuURL= curURL.split("/sfa/")[1];//左菜单链接
	
		if("login".equals(curURL.split("/")[2])){//登录的时候进行菜单初始化
			navURL="/news/index";
		}
		
		StringBuffer buffer = new StringBuffer();
		
		String dir = HeaderTag.class.getResource("/").getPath();
		dir = dir.replace("%20", " ");//对空格进行转义(否则无法识别路径)
		
		String cpath = dir+"menuxml//MenuConfig.xml";
		File f = new File(cpath);

		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(f);
		
		//获取根元素
		Element root = document.getRootElement();
	
		//获取导航菜单
		Element navMenu = (Element) root.selectSingleNode("//Navigation[@Url='"+navURL+"']");
		
		logger.info("navMenu="+navMenu);
		
		//获取当前菜单
		//当前菜单存在三种情况:1.当前菜单为主菜单链接;2.当前菜单为左菜单链接;3.当前菜单不在MenuConfig.xml文件中
		Element currentMenu = (Element) root.selectSingleNode("//Columns/Column[@Url='"+menuURL+"']");
		
		if(CommonUtil.isEmpty(currentMenu)){
			//currentMenu=navMenu.element("Group").element("Columns").element("Column");
			
		}else if(navURL.equals("/"+menuURL)){
			//currentMenu=navMenu.element("Group").element("Columns").element("Column");//TODO:如果为空,设置为第一个菜单项
		}
		
		logger.info("currentMenu="+currentMenu);
		
		//获取所有的导航菜单
		List navList = root.selectNodes("Navigation");
		
		buffer.append("<div id='mqq-navbar'></div>");
		
		buffer.append("<div id='header'>"+
						"<div class='logo'>"+
							"<h1><a href='javascript:void(0);' title=''><img src='"+path+"/images/app-logo.jpg'  height='66' width='289' /></a></h1>"+
						"</div>"+
						"<ul>"
				);

		String navLevel="";
		for(Iterator<Element> iter=navList.iterator();iter.hasNext(); ){
			Element  navElement = iter.next();
			
			navLevel = navElement.attributeValue("level");
			
			if(Arrays.asList(navLevel.split(",")).contains(userType)){
				if(navMenu.attributeValue("Id").equals(navElement.attributeValue("Id"))){
					
					buffer.append("<li class='nownav'><a href='"+path+navElement.attributeValue("Url")+"'><span>"+navElement.attributeValue("Name")+"</span></a>");
				}else{
					buffer.append("<li><a href='"+path+navElement.attributeValue("Url")+"'><span>"+navElement.attributeValue("Name")+"</span></a>");
				}
			}
		}
		buffer.append("</ul></div>");
		
		
		//如果当前是navMenu没有子元素,则不显示左边菜单
		if(CommonUtil.isEmpty(navMenu.element("Group"))){
			
			buffer.append("<div class='decoration'></div>"+
					"<div class='wrap'>"+
					"<p class='bread-nav colorstyle'> 首页&nbsp;&gt;&gt;&nbsp;<a href=''></a>"+navMenu.attributeValue("Name")); 
			buffer.append("</p>"+"<div class='content touch'>");
					
			
			
		}else{

			buffer.append("<div class='decoration'></div>"+
							"<div class='wrap'>"+
							"<p class='bread-nav colorstyle'><a href=''></a>"+navMenu.attributeValue("Name")+"&nbsp;&gt;&gt;&nbsp;<span>"+navMenu.element("Group").element("Name").getText()); 
							if(!CommonUtil.isEmpty(currentMenu)){
								buffer.append("&nbsp;&gt;&gt;&nbsp;<span>"+currentMenu.attributeValue("Name"));
							}
							buffer.append(	"</span></p>"+
							"<div class='content touch'>"+
								"<ul class='left'><li>"
					);
			
			
			List leftMenu =  navMenu.selectNodes("Group");
			for(Iterator<Element> iter =leftMenu.iterator();iter.hasNext(); ){
				Element menu = iter.next();
				Element cols = menu.element("Columns");
				String menuLevel = "1" ;//初始化为最低级别
				buffer.append("<ul>");
				buffer.append("<li class='titleon'><a href='javascript:void(0)'>"+menu.elementText("Name")+"</a></li>");
				List colList = cols.selectNodes("Column");
				for(Iterator<Element> iter2 =colList.iterator();iter2.hasNext();){
					Element col = iter2.next();
					menuLevel = col.attributeValue("level");
					/*class="click"*/
					if(!CommonUtil.isEmpty(currentMenu) && currentMenu.attributeValue("id").equals(col.attributeValue("id"))){	
						if(Arrays.asList(menuLevel.split(",")).contains(userType)){
							buffer.append("<li class='click'><a href='"+path+"/"+col.attributeValue("Url")+"'>"+col.attributeValue("Name")+"</a>");
						}else{
							buffer.append("<li class='click'><a style='color:gray' href='javascript:art.dialog( {"+
									"id : \"loading\","+
									"lock : true,"+
									"drag : false,"+
									"icon: \"error\","+
									"resize : false,"+
									"content : \"对不起,您没有权限进行此操作!\""+
								"});'>"+col.attributeValue("Name")+"</a>");
						}
					}else{	
						if(Arrays.asList(menuLevel.split(",")).contains(userType)){
							buffer.append("<li ><a href='"+path+"/"+col.attributeValue("Url")+"'>"+col.attributeValue("Name")+"</a>");
						}else{
							buffer.append("<li class='click'><a style='color:gray' href='javascript:art.dialog( {"+
									"id : \"loading\","+
									"lock : true,"+
									"drag : false,"+
									"icon: \"error\","+
									"resize : false,"+
									"content : \"对不起,您没有权限进行此操作!\""+
								"});'>"+col.attributeValue("Name")+"</a>");
						}
						
					}
					
				}	
				
				buffer.append("</ul>");
			}
			
			buffer.append("</li>");
			
			buffer.append("</ul>");
		}
		
		buffer.append("<div class='right'>");
		
		JspWriter out = pageContext.getOut();
		 try {
			out.println(buffer);//输出到jsp页面
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		} catch (DocumentException e1) {
			
			e1.printStackTrace();
		}
		
		
		return super.doStartTag();
	}

}
